<?php
/**
	uuid manipulation class
 */
class CUUID {

	/*encode UUID to binary*/
	protected static function packuuid($uuid){
		try{
			return pack('h*',str_replace('-','',$uuid));
		} catch(Exception $e) {
			return false;
		}
	}
	
	/*decode binary to UUID*/
	protected static function unpackuuid($binary, $case = 0){
		$string = unpack('h*', $binary);
		$string = preg_replace('/([0-9a-f]{8})([0-9a-f]{4})([0-9a-f]{4})([0-9a-f]{4})([0-9a-f]{12})/', '$1-$2-$3-$4-$5', $string);		
		return $case ? strtoupper($string[1]) : $string[1];		
	}
	
	protected static function UUID($delimiter=false, $serverID=1){
    $t=explode(' ',microtime());
		$output_format = $delimiter ? '%08s-%04s-%04x-%04x-%12s' : '%08s%04s%04x%04x%12s';
    $output = sprintf($output_format,
        (substr('00000000'.dechex($t[1]),-8)),   // get 8HEX of unixtime
        (substr('0000'.dechex(round($t[0]*65536)),-4)), // get 4HEX of microtime
        mt_rand(0,0xffff),
        $serverID,
        self::clientIPToHex()
				);
		return strtoupper($output);
	}

	protected static function clientIPToHex($client_ip = ''){
			$hex='';
			$client_ip = ($client_ip ? $client_ip : $_SERVER['REMOTE_ADDR']);
			$part=explode('.', $client_ip);
			for ($i=0; $i<=count($part)-1; $i++) {
					$hex.=substr('00'.dechex($part[$i]),-3);
			}
			return $hex;
	}

}